package activity.Left;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;

import com.hichip.campro.R;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import activity.Left.adapter.LocalFileListAdapter;
import base.HiActivity;
import bean.LeftLocalFileBean;
import butterknife.BindView;
import common.HiDataValue;
import common.TitleView;
import utils.HiToast;
import utils.HiTools;

//本地文件列变界面
public class LeftLocalFileActivity extends HiActivity implements AdapterView.OnItemClickListener {
    @BindView(R.id.title) public TitleView title;
    @BindView(R.id.gridview) public GridView gridview;
    private LocalFileListAdapter mAdapter;
    private List<LeftLocalFileBean> leftLocalFileBeans;
    private boolean mIsDelete = false;//是否是编辑状态
    private LeftGetDataModel mModel;
    @BindView(R.id.tv_nothing) public TextView tv_nothing;


    @Override
    protected int setLayoutId() {
        return R.layout.activity_left_local_file;
    }

    @Override
    protected void init(@Nullable Bundle savedInstanceState) {
        initView();
        mModel = LeftGetDataModel.getInstance();
        //准备数据源
        //initData();
        setAdapter();
        setListeners();
    }

    private void setAdapter() {
        leftLocalFileBeans = new ArrayList<>();
        mAdapter = new LocalFileListAdapter(this, leftLocalFileBeans);
        gridview.setAdapter(mAdapter);
        mAdapter.setOnFileDeleteListener(new LocalFileListAdapter.OnFileDeleteListener() {
            @Override
            public void onDelete(boolean isDelete) {
                title.setRightTxt(getString(R.string.edit));
                mIsDelete = false;
            }
        });
    }

    private void setListeners() {
        gridview.setOnItemClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //准备数据源
        leftLocalFileBeans.clear();
        initData();
        if(leftLocalFileBeans.size()<1){
            gridview.setVisibility(View.GONE);
            tv_nothing.setVisibility(View.VISIBLE);
            title.setRightTxtGone();
        }
        mAdapter.notifyDataSetChanged();
        if (HiDataValue.DeleteCameraList != null && HiDataValue.DeleteCameraList.size() > 0) {
            HiDataValue.DeleteCameraList.clear();
        }
    }

    private void initData() {
        if (HiTools.isSDCardExist()) {
            String root_path = getFilesDir() + "/android/data/" + HiDataValue.APP_NAME + "/";
            File file = new File(root_path);
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                for (int i=0;i<files.length;i++) {
                    File file1=files[i];
                    LeftLocalFileBean bean = new LeftLocalFileBean();
                    bean.setUid(file1.getName());
                    bean.setPhotoNum(mModel.getPhotoNum(file1.getAbsolutePath()));
                    bean.setVoideNum(mModel.getVoideNum(file1.getAbsolutePath()));
                    if (mModel.getPhotoNum(file1.getAbsolutePath()) == 0 && mModel.getVoideNum(file1.getAbsolutePath()) == 0) {
                        bean.setSize("0.0 M");
                    } else {
                        bean.setSize(formatDouble4(getDirSize(file1)) + " M");
                    }
                    bean.setPath(getSnapPath(file1.getAbsolutePath() + "/Snapshot/"));
                    bean.setFile(file1);
                    if(bean.getPhotoNum()>0||bean.getVoideNum()>0){
                        leftLocalFileBeans.add(bean);
                    }else{
                        if(file1!=null&&file1.exists()&&file1.isDirectory()){
                            deleteFile(file1);
                        }
                    }
                }
            }
        }
    }

    //flie：要删除的文件夹的所在位置
    private void deleteFile(File file) {
        if(file==null||!file.exists()) return;
        if(file.isDirectory()){
            File[] files=file.listFiles();
            for(int i=0;i<files.length;i++){
                File f=files[i];
                deleteFile(f);
            }
            file.delete();
        }else {
            file.delete();
        }
    }

    private String getSnapPath(String path) {
        String str = "";
        File file = new File(path);
        if (file != null && file.exists()) {
            File[] files = file.listFiles();
            if (files.length > 0) {
                File file1 = files[0];
                str = file1.getName();
                return path + str;
            }
        }
        return str;
    }


    private void initView() {
        title.setButton(TitleView.NAVIGATION_BUTTON_LEFT);
        title.setTitle(getString(R.string.local_file));
        title.setButton(TitleView.NAVIGATION_BUTTON_RIGHT);
        title.setRightTxt(getString(R.string.edit));
        title.setNavigationBarButtonListener(new TitleView.NavigationBarButtonListener() {
            @Override
            public void OnNavigationButtonClick(int which) {
                switch (which) {
                    case TitleView.NAVIGATION_BUTTON_LEFT:
                        finish();
                        break;
                    case TitleView.NAVIGATION_BUTTON_RIGHT:
                        mAdapter.setIsDetele(mIsDelete ? false : true);
                        title.setRightTxt(mIsDelete ? getString(R.string.edit):getString(R.string.finish));
                        mIsDelete = !mIsDelete;
                        break;
                }
            }
        });
    }

    //计算文件夹的大小
    private double getDirSize(File file) {
        //判断文件是否存在
        if (file.exists()) {
            //如果是目录则递归计算其内容的总大小
            if (file.isDirectory()) {
                File[] children = file.listFiles();
                double size = 0;
                for (File f : children)
                    size += getDirSize(f);
                return size;
            } else {//如果是文件则直接返回其大小,以“兆”为单位
                double size = (double) file.length() / 1024 / 1024;
                return size;
            }
        } else {
            return 0.0;
        }
    }

    public static String formatDouble4(double d) {
        //整数部分全部显示，小数部分后面保留1位小数
        return String.format("%.1f", d);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if(mIsDelete) return;
        LeftLocalFileBean bean = leftLocalFileBeans.get(position);
        if (bean == null) return;
        if (bean.getSize().equals("0.0 M")) {
            HiToast.showToast(LeftLocalFileActivity.this, getString(R.string.empty));
        } else {
            Intent intent = new Intent(LeftLocalFileActivity.this, LeftLocalVideoPhotoActivity.class);
            intent.putExtra("bean", bean);
            startActivity(intent);
        }
    }
}
